package online.zhangwenzhe.common.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    Authenticator authenticator;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String authorizationHeader = httpServletRequest.getHeader("Authorization");
        String username = "anonymousUser";

        if (!StringUtils.isEmpty(authorizationHeader)) {
            String token = authorizationHeader.substring(7);
            username = authenticator.verifyToken(token);
        }

        if (StringUtils.isEmpty(username)) {
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().write("token失效");
            return false;
        }

        if (!authenticator.verifyAuthority(username, httpServletRequest.getRequestURI(), httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(403);
            httpServletResponse.getWriter().write("无权访问");
            return false;
        }

        return true;
    }
}
